package net.carinae.dev.seduku.dao;

import java.util.Random;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import net.carinae.dev.seduku.model.Sudoku4;

import org.springframework.stereotype.Repository;

@Repository
public class Sudoku4DaoImpl implements Sudoku4Dao {

	@PersistenceContext
    private EntityManager entityManager;
	
	
	@Override
	public Sudoku4 loadRandom() {
		Sudoku4 ret = null;
		
		Integer count = (Integer)this.entityManager.
				createQuery("select count(s.originalRep) from Sudoku4 s").
				getSingleResult();
		Random rand = new Random(System.currentTimeMillis());
		
		ret = (Sudoku4) this.entityManager.
				createQuery("select s4 from Sudoku4 s4").
				setFirstResult((int)(count*rand.nextFloat())).
				setMaxResults(1).
				getSingleResult();

		ret.init();
		return ret;
	}

	@Override
	public void persist(Sudoku4 sudoku4) {
		
		try {
			this.entityManager.persist(sudoku4);
		} catch (EntityExistsException e) {
			// Already persisted, nothing to do
		}
		
	}

}
